package com.zwb.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwb.service.common.utils.AdminUtil;
import com.zwb.service.mapper.AdminMapper;
import com.zwb.service.pojo.Admin;
import com.zwb.service.pojo.Role;
import com.zwb.service.service.IAdminService;
import com.zwb.service.enums.StatusCode;
import com.zwb.service.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zwb
 * @since 2022-08-23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Autowired(required = false)
    private AdminMapper adminMapper;

    @Autowired
    private IRoleService roleService;


    /**
     * 根据用户名获取 用户
     *
     * @param name
     * @return
     */
    @Override
    public Admin getAdminByUsername(String name) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, name)
                // 要求是启用的
                .eq(Admin::isEnabled, true);
        Admin user = this.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(user)) {
            return user;
        } else {
            // 查询用户对应的角色
            user.setRoles(roleService.getRolesByUserId(user.getId()));
        }
        return user;
    }

    /**
     * 获取所有操作员（当前登录用户除外）
     *
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        Admin currentAdmin = (Admin) AdminUtil.getCurrentAdmin();
        List<Admin> allAdmins = adminMapper.getAllAdmins(currentAdmin.getId(), "%" + keywords + "%");
        if (!ObjectUtils.isEmpty(allAdmins)) {
            // 密码脱敏
            allAdmins.forEach(item -> item.setPassword(null));
        }
        return allAdmins;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Admin admin = this.getAdminByUsername(username);
        if (ObjectUtils.isEmpty(admin)) {
            throw new UsernameNotFoundException(StatusCode.USERNAME_NOT_EXIST.getMessage());
        }
        return admin;
    }
}
